import { _decorator, Component, resources, SpriteFrame } from 'cc'

import { TileItem } from './TileItem'
import { createUINode } from '../../Utils'
import { DataCenter } from '../../Runtime/DataCenter'
const { ccclass, property } = _decorator

@ccclass('TileMap')
export class TileMap extends Component {
  async init() {
    const { mapInfo } = DataCenter
    const tileRes = await this.loadTileRes()
    for (let index = 0; index < mapInfo.length; index++) {
      const row = mapInfo[index]
      for (let j = 0; j < row.length; j++) {
        const tile = row[j]
        if (tile.src == null || tile.type == null) {
          continue
        }
        const node = createUINode()
        const tileItemScript = node.addComponent(TileItem)
        const imgName = `tile (${tile.src})`
        const spriteFrame = tileRes.find(item => item.name == imgName) || tileRes[0]
        tileItemScript.init(spriteFrame, index, j)
        node.parent = this.node
      }
    }
  }
  //加载瓦片资源
  loadTileRes() {
    return new Promise<SpriteFrame[]>((resolve, reject) => {
      resources.loadDir('texture/tile/tile', SpriteFrame, (err, assets) => {
        if (err) {
          reject(err)
          return
        }
        resolve(assets)
      })
    })
  }
}
